package com.youlai.quarkus.system.config;

import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.youlai.quarkus.system.handler.mybatisplus.MyMetaObjectHandler;
import io.quarkiverse.mybatis.plus.MyBatisPlusConfig;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.annotations.Recorder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.eclipse.microprofile.config.inject.ConfigProperty;

/**
 * mybatis-plus 配置类
 *
 * @author haoxr
 * @since 2022/7/2
 */
@Recorder
public class MyBatisPlusRecorder {

    /**
     * 自定义Bean配置
     * https://cn.quarkus.io/guides/writing-extensions#expose-your-components-via-cdi
     */

    @ConfigProperty(name = "system.config.data-permission-enabled", defaultValue = "false")
    boolean dataPermissionEnabled;

    public void initSqlSessionEnhanced(RuntimeValue<SqlSessionFactory> sqlSessionFactory, MyBatisPlusConfig config) {
        Configuration configuration = sqlSessionFactory.getValue().getConfiguration();
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        if (dataPermissionEnabled) {
            interceptor.addInnerInterceptor(new DataPermissionInterceptor());
        }
        GlobalConfigUtils.getGlobalConfig(configuration).setMetaObjectHandler(new MyMetaObjectHandler());
    }

}
